package com.framework.network.interceptor

import android.content.Context
import com.framework.network.annotations.getRetrofitMethod
import com.framework.network.annotations.getRootDomain
import com.framework.network.interceptor.urlinter.CheckUrlUtils
import com.framework.network.interceptor.urlinter.DomainUrlParser
import com.framework.network.manager.NetworkManager
import com.framework.network.utils.NetworkLogUtil
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @Description:设置请求url替换的拦截器
 * @Author: you
 */
class UrlReplaceInterceptor(private val context: Context) : Interceptor {
    private var mUrlParser = DomainUrlParser()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val retrofitMethod = getRetrofitMethod(request) ?: return chain.proceed(request)
        val setRootDomain = getRootDomain(retrofitMethod)
        val rootDomain = if (setRootDomain != null) {
            getRootDomain(setRootDomain)
        } else {
            null
        }
        return if (rootDomain.isNullOrBlank().not()) {
            val domain = NetworkManager.getInstance().create().findDomain(rootDomain)
            if (domain.isNullOrBlank().not()) {
                val newUrl = mUrlParser.parseUrl(
                    CheckUrlUtils.checkUrl(domain!!),
                    chain.request().url
                )
                NetworkLogUtil.debugLog("The new url is { " + newUrl.toString() + " }, old url is { " + chain.request().url.toString() + " }")

                chain.proceed(chain.request().newBuilder().url(newUrl).build())
            } else {
                chain.proceed(chain.request())
            }
        } else {
            chain.proceed(chain.request())
        }
    }
}